<?php

namespace App\Services;

use Auth;
use App\Models\CartItem;
class CartService
{
    /**
     * 当前用户购物车
     *
     * @return mixed
     */
    public function get()
    {
        return Auth::user()->cartItems()->with(['productSku.product'])->get();
    }

    /**
     * 添加购物车
     *
     * @param int $skuId
     * @param int $amount
     * @return array
     */
    public function add(int $skuId, int $amount)
    {
        $user = Auth::user();
        if ($cart = $user->cartItems()->where('product_sku_id', $skuId)->first()){
            $cart->increment('amount', $amount);
        }else{
            $cart = new CartItem(['amount' => $amount]);
            $cart->user()->associate($user);
            $cart->productSku()->associate($skuId);
            $cart->save();
        }

        return $cart;
    }

    /**
     * 移除购物车
     *
     * @param $skuIds int|array
     */
    public function remove($skuIds)
    {
        if (!is_array($skuIds)){
            $skuIds = [$skuIds];
        }

        Auth::user()->cartItems()->whereIn('product_sku_id', $skuIds)->delete();
    }


}